package com.tlvip.arithmetic.ch05;

/**
 * <p>description：使用数组实现的循环队列</p>
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 1/25/21</p>
 * Author mac
 *
 * @version 1.0
 */
public class MyCircleArray {
    int size;
    int head;
    int tail;
    int data[];
    int length;

    public MyCircleArray(int size) {
        this.size = size;
    }

    public void push(int value) {
        // 初始化
        if (data == null || data.length == 0) {
            data = new int[size];
        }
        if (isFull()) {
            System.out.println("queue is full,can not push element");
            return;
        }
        // 向尾节点插入新数据
        data[tail] = value;
        tail = tail + 1;
        // 尾表增加1大于size时，需要重置尾节点
        if (tail >= size) {
            tail = tail % size;
        }
        ++length;
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("queue is empty,can not pop element");
            return -1;
        }
        int element = data[head];
        // 重置成无效值
        data[head] = -1;
        if (++head > size) {
            head = (head - 1) % size;
        }
        --length;
        return element;
    }

    public void print() {
        for (int i : data) {
            if (i != -1) {
                System.out.print(i + "  ");
            }
        }
        System.out.println();
    }

    public boolean isEmpty() {
        return length == 0;
//        return head == tail;
    }

    public boolean isFull() {
        return length == size;
//        return ((tail + 1) % size == head);
    }

    public static void main(String[] args) {
        int size = 6;
        System.out.println("第一次初始化");
        MyCircleArray myCircleArray = new MyCircleArray(size);
        for (int i = 1; i < 8; i++) {
            myCircleArray.push(i);
        }
        System.out.println("第一次输出元素如下");
        myCircleArray.print();
        System.out.println("出队三个元素");
        for (int i = 0; i < 3; i++) {
            System.out.print(myCircleArray.pop() + "  ");
        }
        System.out.println();
        System.out.println("入队三个元素");
        for (int i = 100; i < 104; i++) {
            myCircleArray.push(i);
        }
        System.out.println("第二次输出元素如下");
        myCircleArray.print();
    }

}
